package com.aaa.arouterone.testViewModel

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import java.util.*
import kotlin.concurrent.timerTask

/**
 * @Description:
 * @Author:  lfc
 * @Email:    iamlifuchang@163.com
 * @CreateTime:     2021/3/30 16:51
 * @UpdateRemark:
 */
class MyViewModel : ViewModel() {

    val timer: Timer by lazy {
        Timer()
    }

    //    var currentSecond = 0
    private val currentSecond: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>()
    }
    var counts: Int = 0
    var isStartRunging = false

    private val users: MutableLiveData<List<UsersM>> by lazy {
        MutableLiveData<List<UsersM>>().also {
            loadUsers()
        }
    }

    fun getUsers(): LiveData<List<UsersM>> {
        return users
    }

    fun getCurrentSecond(): LiveData<Int> {
        return currentSecond
    }

    //    开始计时
    fun starttiming() {
        timer?.apply {
            if (!isStartRunging) {
                currentSecond.value=(0)
//                重复启动会报错！
                this.schedule(timerTask, 1000, 1000)
            }
        }


    }

    private var timerTask = kotlin.concurrent.timerTask {
        kotlin.run {
            if (!isStartRunging) isStartRunging = true
            counts++
            currentSecond?.postValue(counts)
//            onTimeChangeListener?.apply {
//                this.onTimerChange(currentSecond)
//            }
        }
    }

    // TODO: 2021/3/31  可以优化为 依赖注入的方式
    lateinit var onTimeChangeListener: OnTimeChangeListener

    interface OnTimeChangeListener {
        fun onTimerChange(second: Int)
    }

    /**
     * 获取用户信息
     */
    private fun loadUsers() {
//        // Do an asynchronous operation to fetch users.
    }

    /**
     * 应该是被清除的时候 使用  这个地方应该是生命周期的最后一步了
     */
    override fun onCleared() {
        super.onCleared()
        Log.d("--lfc", "testViewModel - MyViewModel- onCleared")
        stopTiming()

    }

    fun stopTiming() {
        timer?.cancel()
        isStartRunging = false
    }

}